package client

import (
	"fmt"
	"net"
	"bufio"
	"os"
	"strings"
	"github.com/sirupsen/logrus"
)

func Run() {
	logrus.Info("client run...")

	fmt.Print("Enter your name: ")
	var name string
	fmt.Scanf("%s", &name)
	fmt.Println(name)
	
	address := "10.0.0.127:6657"
	conn, err := net.Dial("tcp", address)
	if err != nil {
		logrus.Errorf("connect to %s fail, err: %v", address, err)
		return
	}
	defer conn.Close()
	
	scanner := bufio.NewScanner(os.Stdin)
	for {
		fmt.Print("Enter message (or type 'quit' to exit): ")
		if !scanner.Scan() {
			break
		}

		message := scanner.Text()
		if strings.ToLower(message) == "quit" {
			break
		}

		message = name + "->" + message + "\n"
		n, err := conn.Write([]byte(message))
		if err != nil {
			logrus.Errorf("write message fail: %v, len: %d", err, n)
			return
		}
		
	}

	if err := scanner.Err(); err != nil {
		logrus.Errorf("input error: %v", err)
	}
}
